package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户地理位置服务接口实现类
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上报地理位置
     */
    @Override
    public void save(Long userId, Double longitude, Double latitude, String addrStr) {
        //1.先根据当前用户id查询地址位置是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        //1.1构造GeoJsonPoint经纬度
        GeoJsonPoint location = new GeoJsonPoint(longitude, latitude);
        //1.2构造时间
        long nowTime = System.currentTimeMillis();
        //2.如果存在则更新
        if (null != userLocation) {
            Update update = new Update();
            update.set("location", location);//经纬度
            update.set("address", addrStr);//中文地址
            update.set("updated", nowTime);//更新时间
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        } else {
            //3.不存在则保存
            userLocation = new UserLocation();
            userLocation.setUserId(userId);//当前用户id
            userLocation.setLocation(location);//经纬度
            userLocation.setAddress(addrStr);//中文位置描述
            userLocation.setCreated(nowTime);//创建时间
            userLocation.setUpdated(nowTime);//更新时间
            mongoTemplate.insert(userLocation);
        }
    }

    /**
     * 搜附近(注意需要排除自己)
     * distance：单位 米
     */
    @Override
    public List<Long> searchNearBy(Long userId, Long distance) {
        //1获取当前用户位置
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();
        //2根据当前用户位置（参数1） 以及 搜索距离(参数2) 构造圆
        Distance dc = new Distance(distance/1000, Metrics.KILOMETERS);
        Circle circle = new Circle(location,dc);
        //3.MongoDB搜索附近的用户列表数据
        Query nearQuery = new Query();
        nearQuery.addCriteria(Criteria.where("userId").ne(userId).and("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(nearQuery, UserLocation.class);
        //4.获取附近用户ids
        return userLocationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());
    }
}
